import Map from 'ol/Map';
import View from 'ol/View';
import Feature from 'ol/Feature';
import VectorSource from 'ol/source/Vector';
import Cluster from 'ol/source/Cluster';
import {Vector as VectorLayer} from 'ol/layer';

/**
 * 点聚合工具类
 */
class ClusterUtil{
  constructor(map,features,distance){
    this.map = map//地图
    this.features = features//要素列表
    this.distance = distance//最小距离
    this._init()
  }

  //初始化
  _init(){
    //创建矢量图层
    //this.vectorLayer = LayerUtil.vectorLayer()
    //this.map.addLayer(this.vectorLayer)

/*
    //创建矢量数据源
    var source = new ol.source.Vector({
      features: this.features
    });
*/

    //创建聚合对象并设置数据源和距离
    var clusterSource = new ol.source.Cluster({
      distance: parseInt(this.distance, 10),
      source: source
    });
    this.clusterSource = clusterSource
    //为图层设置聚合数据源
    this.vectorLayer.setSource(clusterSource)
    var styleCache = {};
    //设置样式
    this.vectorLayer.setStyle(function(feature) {
      var size = feature.get('features').length
      var style = styleCache[size];
      if (!style) {
        style = new ol.style.Style({
          image: new ol.style.Circle({
            radius: 10,
            stroke: new ol.style.Stroke({
              color: '#fff'
            }),
            fill: new ol.style.Fill({
              color: '#3399CC'
            })
          }),
          text: new ol.style.Text({
            text: size.toString(),
            fill: new ol.style.Fill({
              color: '#fff'
            })
          })
        })
        styleCache[size] = style;
      }
      return style;
    })
  }

  //动态修改距离
  setDistance(distance){
    this.distance = distance;
    this.clusterSource.setDistance(parseInt(distance.value, 10));
  }
}
